// src/store/slices/chatSlice.ts
import { createSlice, createAsyncThunk, PayloadAction } from '@reduxjs/toolkit';
import aiService from '../../services/aiService';
import { ChatMessage } from '../../types';

interface Conversation {
  id: string;
  title: string;
  lastMessage: string;
  lastMessageTime: Date;
  messages: ChatMessage[];
}

interface ChatState {
  conversations: Conversation[];
  currentConversation: Conversation | null;
  messages: ChatMessage[];
  isLoading: boolean;
  isSending: boolean;
  error: string | null;
  model: 'gpt-4o-mini';
  typingIndicator: boolean;
  usageToday: number;
  usageLimit: number;
}

const initialState: ChatState = {
  conversations: [],
  currentConversation: null,
  messages: [],
  isLoading: false,
  isSending: false,
  error: null,
  model: 'gpt-4o-mini',
  typingIndicator: false,
  usageToday: 0,
  usageLimit: 10,
};

// 异步actions
export const sendMessage = createAsyncThunk(
  'chat/sendMessage',
  async ({ message, conversationId }: { message: string; conversationId?: string }) => {
    const response = await aiService.chat({
      message,
      conversationId,
      model: initialState.model
    });
    return response;
  }
);

export const loadChatHistory = createAsyncThunk(
  'chat/loadHistory',
  async ({ conversationId, page = 1 }: { conversationId?: string; page?: number }) => {
    const response = await aiService.getChatHistory(conversationId, page);
    return response;
  }
);

export const deleteConversation = createAsyncThunk(
  'chat/deleteConversation',
  async (conversationId: string) => {
    await aiService.deleteChatHistory(conversationId);
    return conversationId;
  }
);

export const fetchUsageStats = createAsyncThunk('chat/fetchUsageStats', async () => {
  const response = await aiService.getUsageStats();
  return response;
});

const chatSlice = createSlice({
  name: 'chat',
  initialState,
  reducers: {
    addMessage: (state, action: PayloadAction<ChatMessage>) => {
      state.messages.push(action.payload);

      // 更新当前对话
      if (state.currentConversation) {
        state.currentConversation.messages.push(action.payload);
        state.currentConversation.lastMessage = action.payload.content;
        state.currentConversation.lastMessageTime = action.payload.timestamp;
      }
    },
    setCurrentConversation: (state, action: PayloadAction<Conversation | null>) => {
      state.currentConversation = action.payload;
      state.messages = action.payload?.messages || [];
    },
    createNewConversation: (state, action: PayloadAction<{ id: string; title: string }>) => {
      const newConversation: Conversation = {
        id: action.payload.id,
        title: action.payload.title,
        lastMessage: '',
        lastMessageTime: new Date(),
        messages: [],
      };
      state.conversations.push(newConversation);
      state.currentConversation = newConversation;
      state.messages = [];
    },
    updateConversationTitle: (
      state,
      action: PayloadAction<{ id: string; title: string }>
    ) => {
      const conversation = state.conversations.find((c) => c.id === action.payload.id);
      if (conversation) {
        conversation.title = action.payload.title;
      }
      if (state.currentConversation?.id === action.payload.id) {
        state.currentConversation.title = action.payload.title;
      }
    },
    setModel: (state, action: PayloadAction<'gpt-4o-mini'>) => {
      state.model = action.payload;
    },
    setTypingIndicator: (state, action: PayloadAction<boolean>) => {
      state.typingIndicator = action.payload;
    },
    clearMessages: (state) => {
      state.messages = [];
      if (state.currentConversation) {
        state.currentConversation.messages = [];
      }
    },
    clearError: (state) => {
      state.error = null;
    },
    resetChat: () => initialState,
  },
  extraReducers: (builder) => {
    builder
      // Send Message
      .addCase(sendMessage.pending, (state) => {
        state.isSending = true;
        state.error = null;
        state.typingIndicator = true;
      })
      .addCase(sendMessage.fulfilled, (state, action) => {
        state.isSending = false;
        state.typingIndicator = false;
        state.usageToday += 1;

        // 添加AI回复
        const aiMessage: ChatMessage = {
          id: Date.now().toString(),
          role: 'assistant',
          content: action.payload.reply,
          timestamp: new Date(),
          tokensUsed: action.payload.usage.tokens,
        };

        state.messages.push(aiMessage);

        if (state.currentConversation) {
          state.currentConversation.messages.push(aiMessage);
          state.currentConversation.lastMessage = aiMessage.content;
          state.currentConversation.lastMessageTime = aiMessage.timestamp;
        }
      })
      .addCase(sendMessage.rejected, (state, action) => {
        state.isSending = false;
        state.typingIndicator = false;
        state.error = action.error.message || '发送失败';
      })
      // Load History
      .addCase(loadChatHistory.pending, (state) => {
        state.isLoading = true;
      })
      .addCase(loadChatHistory.fulfilled, (state, action) => {
        state.isLoading = false;
        state.messages = action.payload.messages;
      })
      .addCase(loadChatHistory.rejected, (state, action) => {
        state.isLoading = false;
        state.error = action.error.message || '加载失败';
      })
      // Delete Conversation
      .addCase(deleteConversation.fulfilled, (state, action) => {
        state.conversations = state.conversations.filter(
          (c) => c.id !== action.payload
        );
        if (state.currentConversation?.id === action.payload) {
          state.currentConversation = null;
          state.messages = [];
        }
      })
      // Fetch Usage Stats
      .addCase(fetchUsageStats.fulfilled, (state, action) => {
        state.usageToday = action.payload.daily.chatCount;
        state.usageLimit = action.payload.limits.dailyChatLimit;
      });
  },
});

export const {
  addMessage,
  setCurrentConversation,
  createNewConversation,
  updateConversationTitle,
  setModel,
  setTypingIndicator,
  clearMessages,
  clearError,
  resetChat,
} = chatSlice.actions;

export default chatSlice.reducer;